package org.jeecg.modules.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.system.entity.SysEmployee;
import org.jeecg.modules.system.service.ISysEmployeeService;
import org.jeecg.modules.system.service.ISysDepartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.Collections;

import com.alibaba.fastjson.JSONObject;
import org.jeecg.common.util.TokenUtils;
import org.jeecg.common.exception.JeecgBootException;
import org.springframework.beans.BeanUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import java.io.File;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.entity.enmus.ExcelType;
import org.apache.poi.ss.usermodel.Workbook;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.util.IpUtils;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.system.entity.LoginEmployee;
import java.util.Date;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.modules.system.service.ISysPermissionService;
import org.jeecg.modules.system.service.ISysDictService;
import org.jeecg.common.system.vo.DictModel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.jeecg.modules.system.entity.SysUserRole;
import org.jeecg.modules.system.service.ISysUserRoleService;

/**
 * 员工管理
 */
@Slf4j
@Api(tags = "员工管理")
@RestController
@RequestMapping("/sys/employee")
public class SysEmployeeController extends JeecgController<SysEmployee, ISysEmployeeService> {

    @Autowired
    private ISysEmployeeService sysEmployeeService;
    
    @Autowired
    private ISysDepartService sysDepartService;
    
    @Autowired
    private RedisUtil redisUtil;
    
    @Autowired
    private ISysPermissionService sysPermissionService;
    
    @Autowired
    private ISysDictService sysDictService;

    @Autowired
    private ISysUserRoleService sysUserRoleService;

    /**
     * 获取员工列表
     *
     * @param sysEmployee
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "员工信息-获取列表")
    @ApiOperation(value = "员工信息-获取列表", notes = "员工信息-获取列表")
    @GetMapping(value = "/list")
    public Result<IPage<SysEmployee>> queryPageList(SysEmployee sysEmployee,
                                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                   HttpServletRequest req) {
        // 如果没有指定工作状态，默认只查询在职员工
        if (sysEmployee.getWorkStatus() == null) {
            sysEmployee.setWorkStatus(1); // 1表示在职
        }

        // 处理部门树形结构查询 - 获取所有子部门ID
        ArrayList<String> departIdList = new ArrayList<>();

        if(sysEmployee.getDepartName() != null){
            SysDepart depart = sysDepartService.getOne(new LambdaQueryWrapper<SysDepart>().eq(SysDepart::getDepartName, sysEmployee.getDepartName()));
            if(depart != null){
                departIdList.add(depart.getId());
            }
        }
        if(oConvertUtils.isNotEmpty(sysEmployee.getDepartId()) && !departIdList.contains(sysEmployee.getDepartId())){
            departIdList.add(sysEmployee.getDepartId());
        }
        if (departIdList != null && departIdList.size() > 0) {
            ArrayList<String> idList = new ArrayList<>();
            for (String departId : departIdList){
                // 获取所有子部门ID
                List<String> childDepartIds = sysDepartService.getSubDepIdsByDepId(departId);
                // 将当前部门ID也加入查询条件
                idList.add(departId);
                idList.addAll(childDepartIds);
            }
            // 重新设置查询条件中的部门列表
            req.setAttribute("departIds", String.join(",", idList));
        }
        
        // 准备分页参数
        Page<SysEmployee> page = new Page<SysEmployee>(pageNo, pageSize);
        
        // 使用自定义的查询方法，关联部门表获取部门名称
        IPage<SysEmployee> pageList = sysEmployeeService.getEmployeePageList(page, sysEmployee);
        return Result.OK(pageList);
    }

    /**
     * 添加
     */
    @AutoLog(value = "员工管理-添加")
    @ApiOperation(value = "员工管理-添加", notes = "员工管理-添加")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody SysEmployee employee) {
        try {
            sysEmployeeService.addEmployee(employee);
            return Result.OK("添加成功！");
        } catch (Exception e) {
            log.error("添加员工失败", e);
            return Result.error("添加失败：" + e.getMessage());
        }
    }

    /**
     * 编辑
     */
    @AutoLog(value = "员工管理-编辑")
    @ApiOperation(value = "员工管理-编辑", notes = "员工管理-编辑")
    @PutMapping(value = "/edit")
    public Result<String> edit(@RequestBody SysEmployee employee) {
        try {
            sysEmployeeService.editEmployee(employee);
            return Result.OK("编辑成功!");
        } catch (Exception e) {
            log.error("编辑员工失败", e);
            return Result.error("编辑失败：" + e.getMessage());
        }
    }

    /**
     * 通过id删除
     */
    @AutoLog(value = "员工管理-通过id删除")
    @ApiOperation(value = "员工管理-通过id删除", notes = "员工管理-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        try {
            sysEmployeeService.deleteEmployee(id);
            return Result.OK("删除成功!");
        } catch (Exception e) {
            log.error("删除员工失败", e);
            return Result.error("删除失败：" + e.getMessage());
        }
    }

    /**
     * 批量删除
     */
    @AutoLog(value = "员工管理-批量删除")
    @ApiOperation(value = "员工管理-批量删除", notes = "员工管理-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        try {
            this.sysEmployeeService.deleteBatchEmployee(ids.split(","));
            return Result.OK("批量删除成功！");
        } catch (Exception e) {
            log.error("批量删除员工失败", e);
            return Result.error("批量删除失败：" + e.getMessage());
        }
    }

    /**
     * 通过id查询
     */
    @AutoLog(value = "员工管理-通过id查询")
    @ApiOperation(value = "员工管理-通过id查询", notes = "员工管理-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<SysEmployee> queryById(@RequestParam(name = "id", required = true) String id) {
        SysEmployee employee = sysEmployeeService.getById(id);
        if (employee == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(employee);
    }

    /**
     * 通过员工编号查询
     */
    @AutoLog(value = "员工管理-通过员工编号查询")
    @ApiOperation(value = "员工管理-通过员工编号查询", notes = "员工管理-通过员工编号查询")
    @GetMapping(value = "/queryByEmpNo")
    public Result<SysEmployee> queryByEmpNo(@RequestParam(name = "empNo", required = true) String empNo) {
        SysEmployee employee = sysEmployeeService.getEmployeeByEmpNo(empNo);
        if (employee == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(employee);
    }

    /**
     * 校验员工编号是否存在
     */
    @GetMapping(value = "/checkEmpNo")
    public Result<Boolean> checkEmpNo(@RequestParam(name = "empNo", required = true) String empNo,
                                     @RequestParam(name = "id", required = false) String id) {
        boolean exist = sysEmployeeService.checkEmpNoExists(empNo, id);
        return Result.OK(exist);
    }

    /**
     * 导出excel
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, SysEmployee employee) {
        // 检查认证信息
        String token = TokenUtils.getTokenByRequest(request);
        if (oConvertUtils.isEmpty(token)) {
            throw new JeecgBootException("Token不能为空!");
        }
        
        // 处理查询参数
        String paramsStr = request.getParameter("paramsStr");
        if (oConvertUtils.isNotEmpty(paramsStr)) {
            try {
                // 解析查询参数
                JSONObject jsonObj = JSONObject.parseObject(paramsStr);
                if (jsonObj != null && jsonObj.containsKey("queryParam")) {
                    JSONObject queryParam = jsonObj.getJSONObject("queryParam");
                    if (queryParam != null) {
                        // 设置查询参数
                        BeanUtils.copyProperties(queryParam, employee);
                        
                        // 处理部门树形结构查询 - 获取所有子部门ID
                        String departId = employee.getDepartId();
                        if (oConvertUtils.isNotEmpty(departId)) {
                            // 获取所有子部门ID
                            List<String> childDepartIds = sysDepartService.getSubDepIdsByDepId(departId);
                            // 将当前部门ID也加入查询条件
                            childDepartIds.add(departId);
                            // 重新设置查询条件中的部门列表
                            request.setAttribute("departIds", String.join(",", childDepartIds));
                        }
                    }
                }
            } catch (Exception e) {
                log.error("解析导出参数失败", e);
            }
        }
        
        // 使用父类的exportXls方法，这个方法已经有完整的处理流程
        try {
            // 查询数据
            QueryWrapper<SysEmployee> queryWrapper = QueryGenerator.initQueryWrapper(employee, request.getParameterMap());
            
            // 过滤选中数据
            String selections = request.getParameter("selections");
            if (oConvertUtils.isNotEmpty(selections)) {
                List<String> selectionList = Arrays.asList(selections.split(","));
                queryWrapper.in("id", selectionList);
            }
            
            List<SysEmployee> pageList = sysEmployeeService.list(queryWrapper);
            
            // 获取部门名称
            if (pageList != null && !pageList.isEmpty()) {
                for (SysEmployee emp : pageList) {
                    if (oConvertUtils.isNotEmpty(emp.getDepartId())) {
                        // 通过部门ID获取部门
                        SysDepart depart = sysDepartService.getById(emp.getDepartId());
                        if (depart != null) {
                            emp.setDepartName(depart.getDepartName());
                        }
                    }
                }
            }
            
            // 调用父类的导出方法
            ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
            // 获取导出用户
            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            
            String title = "员工信息";
            mv.addObject(NormalExcelConstants.FILE_NAME, title); // 文件名
            mv.addObject(NormalExcelConstants.CLASS, SysEmployee.class); // 实体类
            ExportParams exportParams = new ExportParams(title + "列表", "导出人:" + sysUser.getRealname(), title);
            mv.addObject(NormalExcelConstants.PARAMS, exportParams); // 参数
            mv.addObject(NormalExcelConstants.DATA_LIST, pageList); // 数据集合
            return mv;
        } catch (Exception e) {
            log.error("导出Excel异常", e);
            throw new JeecgBootException("导出Excel失败: " + e.getMessage());
        }
    }

    /**
     * 通过excel导入数据
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, SysEmployee.class);
    }

    /**
     * 检查部门是否存在员工
     */
    @GetMapping(value = "/checkDepartHasEmployee")
    public Result<Boolean> checkDepartHasEmployee(@RequestParam(name = "departId", required = true) String departId) {
        boolean hasEmployee = sysEmployeeService.checkDepartHasEmployee(departId);
        return Result.OK(hasEmployee);
    }
    
    /**
     * 根据ID列表获取员工信息
     */
    @AutoLog(value = "员工管理-根据ID列表获取员工信息")
    @ApiOperation(value = "员工管理-根据ID列表获取员工信息", notes = "员工管理-根据ID列表获取员工信息")
    @GetMapping(value = "/getEmployeesByIds")
    public Result<List<SysEmployee>> getEmployeesByIds(@RequestParam(name = "ids") String ids) {
        if (oConvertUtils.isEmpty(ids)) {
            return Result.OK(new ArrayList<>());
        }
        
        String[] idArray = ids.split(",");
        List<String> idList = Arrays.asList(idArray);
        
        // 根据ID列表查询员工信息
        QueryWrapper<SysEmployee> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", idList);
        List<SysEmployee> employeeList = sysEmployeeService.list(queryWrapper);
        
        return Result.OK(employeeList);
    }
    
    /**
     * 获取员工使用的优化软件类型
     * 
     * @param empId 员工ID
     * @return 优化软件类型（0长风 1新格尔）
     */
    @AutoLog(value = "员工管理-获取员工使用的优化软件类型")
    @ApiOperation(value = "员工管理-获取员工使用的优化软件类型", notes = "员工管理-获取员工使用的优化软件类型")
    @GetMapping(value = "/getCurrentOptimizeSoftType")
    public Result<Integer> getCurrentOptimizeSoftType(@RequestParam(name = "empId", required = true) String empId) {
        try {
            // 获取员工信息
            SysEmployee employee = sysEmployeeService.getById(empId);
            if (employee == null) {
                return Result.error("未找到员工信息");
            }
            
            // 返回员工使用的优化软件类型
            Integer optimizeSoftType = employee.getOptimizeSoftType();
            // 如果优化软件类型为空，默认返回长风类型(0)
            return Result.OK(optimizeSoftType != null ? optimizeSoftType : 0);
        } catch (Exception e) {
            log.error("获取员工使用的优化软件类型失败", e);
            return Result.error("获取优化软件类型失败：" + e.getMessage());
        }
    }

    /**
     * 获取当前用户的优化软件类型
     *
     * @return 优化软件类型（0长风 1新格尔）
     */
    @AutoLog(value = "获取当前用户的优化软件类型")
    @ApiOperation(value = "获取当前用户的优化软件类型", notes = "获取当前用户的优化软件类型")
    @GetMapping(value = "/getCurrentUserOptimizeSoftType")
    public Result<Integer> getCurrentUserOptimizeSoftType() {
        // 获取员工信息
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        SysEmployee employee = sysEmployeeService.getById(sysUser.getId());
        if (employee == null) {
            return Result.error("未找到员工信息");
        }
        
        Integer optimizeSoftType = employee.getOptimizeSoftType();
        // 如果为空，默认为0（长风优化软件）
        if (optimizeSoftType == null) {
            optimizeSoftType = 0;
        }
        
        return Result.OK(optimizeSoftType);
    }

    /**
     * 更新当前用户的优化软件类型
     *
     * @param jsonObject 包含优化软件类型的JSON对象
     * @return 更新结果
     */
    @AutoLog(value = "更新当前用户的优化软件类型")
    @ApiOperation(value = "更新当前用户的优化软件类型", notes = "更新当前用户的优化软件类型")
    @PostMapping(value = "/updateCurrentUserOptimizeSoftType")
    public Result<?> updateCurrentUserOptimizeSoftType(@RequestBody JSONObject jsonObject, HttpServletRequest request) {
        // 从请求体中获取优化软件类型
        String optimizeSoftType = jsonObject.getString("optimizeSoftType");
        if (StringUtils.isBlank(optimizeSoftType)) {
            return Result.error("优化软件类型不能为空");
        }
        
        Integer optimizeType = Integer.parseInt(optimizeSoftType);
        
        // 从请求头获取token
        String token = request.getHeader(CommonConstant.X_ACCESS_TOKEN);
        if (StringUtils.isBlank(token)) {
            return Result.error("未找到有效的token");
        }
        
        // 从Redis中获取员工信息
        Object employeeInfoObj = redisUtil.get(CommonConstant.PREFIX_EMPLOYEE_INFO + token);
        if (employeeInfoObj == null) {
            return Result.error("员工信息已过期，请重新登录");
        }
        
        String employeeInfoJson = employeeInfoObj.toString();
        LoginEmployee loginEmployee = JSONObject.parseObject(employeeInfoJson, LoginEmployee.class);
        String empId = loginEmployee.getId();
        
        // 验证优化软件类型值是否有效
        if (optimizeType != 0 && optimizeType != 1) {
            return Result.error("无效的优化软件类型值");
        }
        
        // 获取员工信息
        SysEmployee employee = sysEmployeeService.getById(empId);
        if (employee == null) {
            return Result.error("未找到员工信息");
        }
        
        // 更新优化软件类型
        employee.setOptimizeSoftType(optimizeType);
        boolean success = sysEmployeeService.updateById(employee);
        
        if (success) {
            // 更新Redis中的员工信息
            loginEmployee.setOptimizeSoftType(optimizeType);
            redisUtil.set(CommonConstant.PREFIX_EMPLOYEE_INFO + token, JSONObject.toJSONString(loginEmployee));
            
            return Result.OK("更新成功");
        } else {
            return Result.error("更新失败");
        }
    }

    /**
     * 获取当前用户的门窗生产类型
     *
     * @param request HTTP请求对象
     * @return 门窗生产类型
     */
    @AutoLog(value = "获取当前用户的门窗生产类型")
    @ApiOperation(value = "获取当前用户的门窗生产类型", notes = "获取当前用户的门窗生产类型")
    @GetMapping(value = "/getCurrentUserWindowDoorType")
    public Result<Integer> getCurrentUserWindowDoorType(HttpServletRequest request) {
        // 从请求头获取token
        String token = request.getHeader(CommonConstant.X_ACCESS_TOKEN);
        if (StringUtils.isBlank(token)) {
            return Result.error("未找到有效的token");
        }
        
        // 从Redis中获取员工信息
        Object employeeInfoObj = redisUtil.get(CommonConstant.PREFIX_EMPLOYEE_INFO + token);
        if (employeeInfoObj == null) {
            return Result.error("员工信息已过期，请重新登录");
        }
        
        String employeeInfoJson = employeeInfoObj.toString();
        LoginEmployee loginEmployee = JSONObject.parseObject(employeeInfoJson, LoginEmployee.class);
        String empId = loginEmployee.getId();
        
        // 获取员工信息
        SysEmployee employee = sysEmployeeService.getById(empId);
        if (employee == null) {
            return Result.error("未找到员工信息");
        }
        
        // 返回门窗生产类型，默认为0（窗户）
        Integer windowDoorType = employee.getWindowDoorType();
        if (windowDoorType == null) {
            windowDoorType = 0;
        }
        
        return Result.OK(windowDoorType);
    }

    /**
     * 更新当前用户的门窗生产类型
     *
     * @param jsonObject 包含门窗生产类型的JSON对象
     * @return 更新结果
     */
    @AutoLog(value = "更新当前用户的门窗生产类型")
    @ApiOperation(value = "更新当前用户的门窗生产类型", notes = "更新当前用户的门窗生产类型")
    @PostMapping(value = "/updateCurrentUserWindowDoorType")
    public Result<?> updateCurrentUserWindowDoorType(@RequestBody JSONObject jsonObject, HttpServletRequest request) {
        // 从请求体中获取门窗生产类型
        String windowDoorType = jsonObject.getString("windowDoorType");
        if (StringUtils.isBlank(windowDoorType)) {
            return Result.error("门窗生产类型不能为空");
        }
        
        Integer doorType = Integer.parseInt(windowDoorType);
        
        // 从请求头获取token
        String token = request.getHeader(CommonConstant.X_ACCESS_TOKEN);
        if (StringUtils.isBlank(token)) {
            return Result.error("未找到有效的token");
        }
        
        // 从Redis中获取员工信息
        Object employeeInfoObj = redisUtil.get(CommonConstant.PREFIX_EMPLOYEE_INFO + token);
        if (employeeInfoObj == null) {
            return Result.error("员工信息已过期，请重新登录");
        }
        
        String employeeInfoJson = employeeInfoObj.toString();
        LoginEmployee loginEmployee = JSONObject.parseObject(employeeInfoJson, LoginEmployee.class);
        String empId = loginEmployee.getId();
        
        // 验证门窗生产类型值是否有效
        if (doorType != 0 && doorType != 1) {
            return Result.error("无效的门窗生产类型值");
        }
        
        // 获取员工信息
        SysEmployee employee = sysEmployeeService.getById(empId);
        if (employee == null) {
            return Result.error("未找到员工信息");
        }
        
        // 更新门窗生产类型
        employee.setWindowDoorType(doorType);
        boolean success = sysEmployeeService.updateById(employee);
        
        if (success) {
            // 更新Redis中的员工信息
            loginEmployee.setWindowDoorType(doorType);
            redisUtil.set(CommonConstant.PREFIX_EMPLOYEE_INFO + token, JSONObject.toJSONString(loginEmployee));
            
            return Result.OK("更新成功");
        } else {
            return Result.error("更新失败");
        }
    }

    /**
     * 重置员工密码
     *
     * @param empId 员工ID
     * @return 重置结果
     */
    @AutoLog(value = "重置员工密码")
    @ApiOperation(value = "重置员工密码", notes = "重置员工密码为员工编号")
    @PostMapping(value = "/resetPassword")
    public Result<?> resetPassword(@RequestParam(name = "empId") String empId) {
        // 校验权限
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (sysUser == null) {
            return Result.error("未登录或登录已过期");
        }
        
        // 获取员工信息
        SysEmployee employee = sysEmployeeService.getById(empId);
        if (employee == null) {
            return Result.error("未找到员工信息");
        }
        
        // 重置密码为员工编号
        boolean success = sysEmployeeService.updateEmployeePassword(empId, employee.getEmpNo());
        
        if (success) {
            return Result.OK("密码重置成功，新密码为员工编号");
        } else {
            return Result.error("密码重置失败");
        }
    }

    /**
     * 通过username查询员工信息
     */
    @AutoLog(value = "员工管理-通过用户账号查询员工信息")
    @ApiOperation(value = "员工管理-通过用户账号查询员工信息", notes = "员工管理-通过用户账号查询员工信息")
    @GetMapping(value = "/queryByUsername")
    public Result<SysEmployee> queryByUsername(@RequestParam(name = "username", required = true) String username) {
        // 根据用户账号查询员工信息
        QueryWrapper<SysEmployee> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        SysEmployee employee = sysEmployeeService.getOne(queryWrapper);
        
        if (employee == null) {
            return Result.error("未找到对应员工信息");
        }
        return Result.OK(employee);
    }

    /**
     * 通过id查询员工信息
     */
    @AutoLog(value = "员工管理-通过id查询员工信息")
    @ApiOperation(value = "员工管理-通过id查询员工信息", notes = "员工管理-通过id查询员工信息")
    @GetMapping(value = "/getEmployeeById")
    public Result<SysEmployee> getEmployeeById(@RequestParam(name = "id", required = true) String id) {
        // 根据id查询员工信息
        SysEmployee employee = sysEmployeeService.getById(id);
        
        if (employee == null) {
            return Result.error("未找到对应员工信息");
        }
        return Result.OK(employee);
    }

    /**
     * 检查登录账号是否已存在
     */
    @GetMapping(value = "/checkUsername")
    public Result<Boolean> checkUsername(@RequestParam(name="username") String username) {
        // 构建查询条件
        LambdaQueryWrapper<SysEmployee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysEmployee::getUsername, username);
        
        // 查询是否存在该登录账号
        Long count = sysEmployeeService.count(queryWrapper);
        
        return Result.OK(count > 0);
    }

    /**
     * 获取角色关联的员工列表
     *
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "员工管理-获取角色关联的员工列表")
    @ApiOperation(value = "员工管理-获取角色关联的员工列表", notes = "员工管理-获取角色关联的员工列表")
    @GetMapping(value = "/employeeRoleList")
    public Result<IPage<SysEmployee>> employeeRoleList(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                              @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                              HttpServletRequest req) {
        Result<IPage<SysEmployee>> result = new Result<IPage<SysEmployee>>();
        Page<SysEmployee> page = new Page<SysEmployee>(pageNo, pageSize);
        String roleId = req.getParameter("roleId");
        String empNo = req.getParameter("empNo");
        IPage<SysEmployee> pageList = sysEmployeeService.getEmployeeByRoleId(page, roleId, empNo);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    /**
     * 查询员工的角色列表
     *
     * @param employeeId 员工ID
     * @return 角色ID列表
     */
    @AutoLog(value = "员工管理-查询员工角色列表")
    @ApiOperation(value = "员工管理-查询员工角色列表", notes = "员工管理-查询员工角色列表")
    @RequestMapping(value = "/queryEmployeeRole", method = RequestMethod.GET)
    public Result<List<String>> queryEmployeeRole(@RequestParam(name = "employeeId", required = true) String employeeId) {
        Result<List<String>> result = new Result<>();
        List<String> list = new ArrayList<String>();
        // 根据员工ID查询用户角色关系表
        QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysUserRole::getUserId, employeeId);
        
        List<SysUserRole> userRoleList = sysUserRoleService.list(queryWrapper);
        if (userRoleList == null || userRoleList.isEmpty()) {
            result.setSuccess(true);
            result.setResult(list);
            return result;
        }
        
        // 提取角色ID列表
        for (SysUserRole sysUserRole : userRoleList) {
            list.add(sysUserRole.getRoleId());
        }
        result.setSuccess(true);
        result.setResult(list);
        return result;
    }
} 